package com.sofwin.configer;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @packageName: com.sofwin.configer
 * @user: andyliu
 * @date: 2021/12/13 15:12
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
// 用于加载外部配置文件
@PropertySource("classpath:jdbc.properties")
@MapperScan({"com.sofwin.mapper","com.sofwin.system.mapper"})
@EnableAspectJAutoProxy
public class MybatisConfiger {
    @Value("com.mysql.cj.jdbc.Driver")
    private String driver;
    @Value("jdbc:mysql://localhost/rbac2107q")
    private String url;
    @Value("root")
    private String username;
    @Value("123456")
    private String password;

    @Bean
    public DataSource getDruidDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
    @Bean
    public PageInterceptor getPageInterceptor(){
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties pros = new Properties();
        pros.put("helperDialect","mysql");
        pageInterceptor.setProperties(pros);
        return pageInterceptor;
    }
    @Bean
    public SqlSessionFactoryBean sqlSession(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(this.getDruidDataSource());
        Resource resource = new ClassPathResource("mybatis-config.xml");
        bean.setConfigLocation(resource);
        bean.setTypeAliasesPackage("com.sofwin.pojo");
        bean.setPlugins(this.getPageInterceptor());
        return bean;
    }
    @Bean
    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager= new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(this.getDruidDataSource());
        return dataSourceTransactionManager;
    }
}
